import 'dart:io';

import 'package:app/http/response_handler.dart';
import 'package:app/models/pagination.dart';
import 'package:app/models/project.dart';
import 'package:app/models/response.dart';
import 'package:app/models/user.dart';
import 'package:app/store/index.dart';
import 'package:app/widgets/message.dart';
import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ApiService {
  static final ApiService _instance = ApiService._internal();
  BuildContext? context;
  bool? isShowLoading;

  factory ApiService([BuildContext? context, bool isShowLoading = true]) {
    _instance.isShowLoading = isShowLoading;
    _instance.context = context;
    return _instance;
  }

  ApiService._internal();

  Dio dio = Dio(BaseOptions(
      // baseUrl: "https://dev.xianghuoai.com",
      baseUrl: "http://uk.frp.one:49156",
      connectTimeout: const Duration(seconds: 15)));

  init() {
    // 请求头添加token
    // dio.options.headers[HttpHeaders.authorizationHeader] = Global.profile.token;

    // 请求头添加content-type
    // dio.options.headers[HttpHeaders.contentTypeHeader] = 'application/json';
    // 忽略证书错误(开发环境使用)
    (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
        (client) {
      client.badCertificateCallback =
          (X509Certificate cert, String host, int port) => true;
      return client;
    };
    // 添加响应拦截器
    dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) {
      // 携带token
      UserModel user = Provider.of<UserModel>(context!, listen: false);
      print('用户Token ${user.token} using Dio.');

      if (user.token != null) {
        options.headers[HttpHeaders.authorizationHeader] = "${user.token}";
      }
      // 在请求发送前打印信息
      print('Requesting to ${options.headers} using Dio.');
      if (isShowLoading == true) {
        Message.showLoading();
      }
      return handler.next(options);
    }, onResponse: (response, handler) {
      // 请求成功
      print("response.data: ${response.data}");
      // 请求成功后，根据状态码处理响应数据
      ResponseHandler.handleResponse(
          context: context,
          responseData: ResponseData.fromJson(response.data, null));
      if (isShowLoading == true) {
        Message.hideLoading();
      }
      return handler.next(response);
    }, onError: (error, handler) {
      // 请求失败
      print(
          'Error occurred while requesting ${error.requestOptions.uri} using Dio.');
      int? statusCode = error.response?.statusCode;
      ResponseHandler.handleError(context: context, statusCode: statusCode);
      Message.hideLoading();
      return handler.next(error);
    }));
  }

  /// 获取验证码
  Future<ResponseData<String>> getCaptcha(String phoneNum) async {
    // 设置请求头为表单格式
    dio.options.headers[HttpHeaders.contentTypeHeader] =
        "application/x-www-form-urlencoded";
    Response<Map<String, dynamic>> result = await dio.post("/auth/sendvcode",
        data: FormData.fromMap({"phoneNum": phoneNum}));
    return ResponseData<String>.fromJson(result.data!, null);
  }

  /// 登录
  Future<ResponseData<String>> login(String phoneNum, String vcode) async {
    print("login: phoneNum: $phoneNum, vcode: $vcode");
    dio.options.headers[HttpHeaders.contentTypeHeader] =
        "application/x-www-form-urlencoded";
    Response<Map<String, dynamic>> result = await dio.post("/auth/login",
        data: FormData.fromMap({"phoneNum": phoneNum, "vcode": vcode}));

    return ResponseData<String>.fromJson(result.data!, null);
  }

  /// 获取用户信息
  Future<ResponseData<UserInfo>> getUserInfo() async {
    dio.options.headers[HttpHeaders.contentTypeHeader] =
        "application/x-www-form-urlencoded";
    Response<Map<String, dynamic>> result = await dio.post("/auth/getuserinfo");
    return ResponseData<UserInfo>.fromJson(result.data!, UserInfo.fromJson);
  }

  // 更新用户信息
  Future<ResponseData<Object>> updateUserInfo(UserInfo userInfo) async {
    print("更新用户信息: userInfo: ${userInfo.toJson()}");
    dio.options.headers[HttpHeaders.contentTypeHeader] =
        "application/x-www-form-urlencoded";
    Response<Map<String, dynamic>> result = await dio.post("/userinfo/upt",
        data: FormData.fromMap(userInfo.toJson()));
    return ResponseData<Object>.fromJson(result.data!, null);
  }

  // 给邮箱发送验证码
  Future<ResponseData<Object>> sendEmailVcode(String email) async {
    dio.options.headers[HttpHeaders.contentTypeHeader] =
        "application/x-www-form-urlencoded";
    Response<Map<String, dynamic>> result = await dio.post(
        "/userinfo/send_email_code",
        data: FormData.fromMap({"email": email}));
    return ResponseData<Object>.fromJson(result.data!, null);
  }

  /// 退出登录(TODO)
  Future<void> loginOut() async {
    await Future.delayed(const Duration(seconds: 2));
  }

  // 创建&更新项目
  Future<ResponseData<Object>> createOrUpdateProject(Project data) async {
    print("创建项目数据： ${data.toJson()}");
    dio.options.headers[HttpHeaders.contentTypeHeader] =
        "application/x-www-form-urlencoded";
    Response<Map<String, dynamic>> result =
        await dio.post("/project/add", data: FormData.fromMap(data.toJson()));
    return ResponseData<Object>.fromJson(result.data!, null);
  }

  // 获取项目列表
  Future<ResponseData<ResponseListData<Project>>> getProjectList(
      Pagination pagination) async {
    dio.options.headers[HttpHeaders.contentTypeHeader] =
        "application/x-www-form-urlencoded";
    print("获取项目列表页码信息： ${pagination.toJson()}");
    Response<Map<String, dynamic>> result =
        await dio.post("/project/list", data: pagination.toJson());
    return ResponseData<ResponseListData<Project>>.fromJson(
        result.data!,
        (Map<String, dynamic> data) =>
            ResponseListData.fromJson(data, Project.fromJson));
  }

  // // 获取项目详情
  // Future<ResponseData<Project>> getProjectDetail(int id) async {
  //   dio.options.headers[HttpHeaders.contentTypeHeader] =
  //       "application/x-www-form-urlencoded";
  //   Response<Map<String, dynamic>> result = await dio.post(
  //       "/project/get_detail", data: FormData.fromMap({"id": id}));
  //   return ResponseData<Project>.fromJson(result.data!, Project.fromJson);
  // }

  // // 删除项目
  // Future<ResponseData<Object>> deleteProject(int id) async {
  //   dio.options.headers[HttpHeaders.contentTypeHeader] =
  //       "application/x-www-form-urlencoded";
  //   Response<Map<String, dynamic>> result = await dio.post(
  //       "/project/delete", data: FormData.fromMap({"id": id}));
  //   return ResponseData<Object>.fromJson(result.data!, null);
  // }

  // // 获取项目成员列表
  // Future<ResponseData<List<User>>> getProjectMemberList(int id) async {
  //   dio.options.headers[HttpHeaders.contentTypeHeader] =
  //       "application/x-www-form-urlencoded";
  //   Response<Map<String, dynamic>> result = await dio.post(
  //       "/project/get_member_list", data: FormData.fromMap({"id": id}));
  //   return ResponseData<List<User>>.fromJson(result.data!, (data) {
  //     List<User> users = [];
  //     data.forEach((key, value) {
  //       users.add(User.fromJson(value));
  //     });
  //     return users;
  //   });
  // }
}
